<?
/**
 * The file contains VC extension for Wordpress
 * 
 * @package	VC
 * @author	cryonyx
 */

require_once(dirname(__FILE__) . '/vc.core.class.php');
require_once(dirname(__FILE__) . '/vc.data.driver.class.php');

//	We need logger class plugged in so that logger functionality works fine 
require_once(dirname(__FILE__) . "/vc.logger.class.php");

class vc_wordpress extends vc_core {
	
	private	$dataDriver;
	
	public function __construct($autosave = FALSE) {
		$this->autosave		=	$autosave;
		$this->dataDriver	=	new	vc_data_driver();
	}
	
	public function saveData() {
		if(	count($this->statistics) == 0	) {
			return FALSE;
		}
		
		global $wpdb, $table_prefix;
		
		$dataToSave	=	$this->dataDriver->batchCompress( $this->statistics );
		foreach($dataToSave as $key => $data) {
			$lineExists	=	$wpdb->get_var(
				"SELECT COUNT(*) FROM `{$table_prefix}vc_data` WHERE `id` = '{$key}';"
			);
			
			if(	!isset($lineExists)	||
				(0	==	intval($lineExists))
			) {			//	Statistics for this entry does not exists in database. Inserting...
				
				$wpdb->query(
					"INSERT INTO `{$table_prefix}vc_data`(`id`,`data`) VALUES('{$key}','{$data}');"
				);
				
				self::logThis("Inserting new statistics for entry with ID " . $key, 0, "vc_wordpress::saveData()");
				
			} else {	//	...otherwise, updating
				
				$wpdb->query(
					"UPDATE `{$table_prefix}vc_data` SET `id`='{$key}', `data`='{$data}' WHERE `id` = '{$key}';"
				);
				
				self::logThis("Updating statistics for entry with ID " . $key, 0, "vc_wordpress::saveData()");
			}
		}
	}
	
	public function loadData() {
		global $wpdb, $table_prefix;
		
		$tmp	=	$wpdb->get_results(
			'SELECT `id`,`data` FROM `' . $table_prefix . 'vc_data`;',
			ARRAY_N
		);
		
		$rawData	=	array();
		foreach($tmp as $line) {
			$rawData[$tmp[0]]	=	$tmp[1];
		}
		
		$this->statistics	=	$this->dataDriver->batchDecompress($rawData);
		
		return TRUE;
	}
	
	/**
	 * Logs a message using a specific log driver
	 *
	 * @param string	$message	Message to log
	 * @param integer	$severity	Message severity
	 * @param string	$place		Where event has occured
	 */
	private function logThis($message, $severity, $place) {
		if(isset($this->logger)) {
			$this->logger->log($message, $severity, $place);
		}
	}
	
	public function getFunnyPictureURL() {
		$url	=	bloginfo('url');
		if('/' !=	substr($url, -1)) {
			$url	.=	'/';
		}
		
		return ($url . 'wp-content/vc/vc.gif');
	}
	
	public function getFunnyPicture() {
		$url		=	self::getFunnyPictureURL();
		$version	=	self::getVersion();
		$retval		=<<<HTML
<a href="http://projects.cerebrate.ru/vc/" title="This site uses Views Counter v. {$version}">
	<img src="{$url}" alt="VC v. {$version}" class="vc-pct" />
</a>
HTML;
		return $retval;
	}
}
?>